package com.zh.common.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import com.zh.common.base.BaseActivity;
import java.util.HashMap;
import java.util.Map;

public class ActManager {

    private static final ActManager instance = new ActManager();

    public static ActManager getInstance() {
        return instance;
    }

    Map<String, Activity> mArrayMap = new HashMap<>();

    /**
     * 把Activity添加到管理中
     */
    public void add(Activity activity) {
        if (activity != null) {
            //如果是 MyActivity 则缓存起来
            if (activity instanceof BaseActivity) {
                String tag = ((BaseActivity) activity).getTag();
                //存入内存中
                mArrayMap.put(tag, activity);
            }
        }
    }

    /**
     * 判断 tag绑定的 MyActivity是否存在
     */
    public boolean isActive(String tag) {
        Activity activity = mArrayMap.get(tag);
        if (activity != null) {
            //判断是否为 MyActivity,如果已经销毁，则移除
            if (activity.isFinishing() || activity.isDestroyed()) {
                mArrayMap.remove(tag);
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }

    /**
     * 找到tag 绑定的 Activity ，通过 getTaskId() 移动到前台
     */
    public void resumeActivity(String tag) {
        Activity activity = mArrayMap.get(tag);
        if (activity != null && !activity.isFinishing() && !activity.isDestroyed()) {
            ActivityManager am = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);
            //返回启动它的根任务（home 或者 MainActivity）
            am.moveTaskToFront(activity.getTaskId(), ActivityManager.MOVE_TASK_NO_USER_ACTION);
        }
    }

    /**
     * 结束指定Activity
     */
    public void finish(Activity activity) {
        try {
            if (activity != null && !activity.isFinishing() && !activity.isDestroyed()) {
                //根据tag 移除 MyActivity
                if (activity instanceof BaseActivity) {
                    String tag = ((BaseActivity) activity).getTag();
                    mArrayMap.remove(tag);
                }
                activity.finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 结束指定Activity
     */
    public void removeTag(Activity activity) {
        try {
            //根据tag 移除 MyActivity
            if (activity instanceof BaseActivity) {
                String tag = ((BaseActivity) activity).getTag();
                mArrayMap.remove(tag);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
